import { Component, HostListener, OnChanges, OnDestroy, OnInit, SimpleChanges } from '@angular/core';
import { Subscription } from 'rxjs';
import { MemberVo } from 'src/app/model/member-vo';
import { MemberStorageService } from 'src/app/services/member-storage.service';
import { MessageNoticeService } from 'src/app/services/message-notice.service';
@Component({
  selector: 'app-member-notice-message',
  template: '<sup class="device-notice-ele" *ngIf="counter>0">{{counter}}</sup>',
  styles: [``]
})
export class MemberNoticeMessageComponent implements OnInit, OnDestroy, OnChanges {
  public counter: number = 0;
  private messageNoticeSubscription!: Subscription;
  /**
   * 未读消息数量组件
   * @param messageNoticeService 
   * @param memberStorage 
   */
  constructor(private messageNoticeService: MessageNoticeService, private memberStorage: MemberStorageService) {
    let curMember: MemberVo | null = this.memberStorage.get();
    this.messageNoticeService.start(curMember?.id??0);
  }

  ngOnChanges(changes: SimpleChanges): void {
    //console.log('[MemberNoticeMessage-CTL]is changed');
    this.notice();
  }

  ngOnDestroy(): void {
    //console.log('[MemberNoticeMessage-CTL]is destory');
    this.messageNoticeService.disconnect();
    if(this.messageNoticeSubscription){
      this.messageNoticeSubscription.unsubscribe();
    }
  }

  ngOnInit(): void {
    //console.log('[MemberNoticeMessage-CTL]is init');
    this.notice();
  }

  //关闭浏览器
  @HostListener('window:beforeunload', ['$event'])
  public closeBrowse(event:Event){
    //console.log('[MemberNoticeMessage-CTL]browse close');
    this.messageNoticeService.disconnect();
    if(this.messageNoticeSubscription){
      this.messageNoticeSubscription.unsubscribe();
    }
  }

  //订阅未读的消息数量
  private notice() {
    this.messageNoticeSubscription = this.messageNoticeService.query().subscribe(counter=>{
      //console.log('[MemberNoticeMessage-CTL]unread message:'+counter);
      this.counter = counter;
    });
  }
}
